<?php

class LoginController extends Zend_Controller_Action
{
    
       protected $session;
    
    public function preDispatch() {
        $this->session = new Zend_Session_Namespace('Default');               
    }

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
    }

    public function loginAction()
    {
        $user = $this->getRequest()->getParam('user');
        $pass = $this->getRequest()->getParam('pass');
        $pass = 'md5:'.md5($pass);        
                
        try{
            $wsdl = 'http://heinsohn.processmaker:80/sysmapeo/en/green/services/wsdl2'; // local
//            $wsdl = 'http://heinsohn.processmaker:80/sysmapeo/en/green/services/wsdl2'; // pruebas
//            $wsdl = 'https://procesos.heinsohn.com.co/sysheinsohn/en/green/services/wsdl2'; // produccion
        
            $soap = new Zend_Soap_Client($wsdl);
            
            $params = array('userid' => $user, 'password' => $pass);

            $result = $soap->login($params);
            
            if($result->status_code == 0){
                //Almacenar usuario en sesion
                
                $sessionid = $result->message;
                
                $_SESSION['sessionid'] = $sessionid;
                $_SESSION['username'] = $user;
                
                Zend_Registry::set('sessionid', $sessionid);
                Zend_Registry::set('username', $user);
                
                $msession = new Model_Session();

                $existe = $msession->sessionExists($user);                
                
                if(0 == $existe){
                    $data = array(
                        'USERNAME' => $user,
                        'SESSION_ID' => $sessionid,
                        'DLOGIN' => new Zend_Db_Expr('NOW()')
                    );
                    $msession->insert($data);
                }else{
                    $data = array(
                        'USERNAME' => $user,
                        'SESSION_ID' => $sessionid,
                        'DLOGIN' => new Zend_Db_Expr('NOW()')
                    );
                    
                    $msession->update($data, "USERNAME = '".$user."'");                    
                }
                
                $login = true;
            }else{
                $login = false;
            }
                                    
            $msg = 1;
            $success = true;
        }catch(Exception $e){
            $success = false;
            $login = false;
            $msg = $e->getMessage();
        }                
        
        $response = array(
            'success' => $success,
            'msg' => $msg,
            'login' => $login
        );
        
        
        $this->_helper->json->sendJson($response);
    }


}